import React from 'react';
import {connect} from 'dva';
import {Link} from 'dva/router'
import {
    Layout,
    Menu,
    Dropdown,
    Icon,
    Affix,
    Badge,
    Popover,
    Card,
    Row,
    Col,
    Breadcrumb,
    Button,
    Form,
    Modal,
    Input,
    TreeSelect,
    Select
} from 'antd';
import '../assets/iconfont/iconfont.css'
import './app.css'
import validator from '../utils/Validator'

import {message} from "antd";

const {Header, Footer, Sider, Content} = Layout;
const SubMenu = Menu.SubMenu;
const MenuItemGroup = Menu.ItemGroup;
const FormItem = Form.Item;
const R = require("ramda");
const TreeNode = TreeSelect.TreeNode;
const App = ({routes, params, children, location, dispatch, app}) => {

    let {layoutMode, isDisplayBreadcrumb, menus, menuSelect, showResetPassword, editModel, userName} = app;
    menus=sessionStorage.menuTree?JSON.parse(sessionStorage.menuTree):menus //todo 判断有无菜单树

    let selectMenus = [];
    let selectOpenMenu = [];
    let openTopMenu = [];
    const convertOrganizations = (node) => {
        let newNode = {
            label: node.orgName,
            value: node.orgId,
            key: node.orgId,
            children: node.children && node.children.length > 0 ? node.children.map(treeNode => convertOrganizations(treeNode)) : []
        };
        return newNode;
    };
    const sideMenus = (() => {
        for (let i = 0; i < menus.length; i++) {
            let menu = menus[i];
            if (menu.children.length > 0) {
                for (let j = 0; j < menu.children.length; j++) {
                    let smenu = menu.children[j];
                    if (location.pathname.includes(smenu.url)) {
                        selectMenus = [smenu.menuId + ""];
                        openTopMenu = [menu.menuId + ""];
                        return menu.children;
                    } else {
                        for (let k = 0; k < smenu.children.length; k++) {
                            let tmenu = smenu.children[k];
                            if (location.pathname.includes(tmenu.url)) {
                                selectMenus = [smenu.menuId + "", tmenu.menuId + ""];
                                selectOpenMenu = [smenu.menuId];
                                openTopMenu = [menu.menuId + ""];
                                return menu.children;
                            }
                        }
                    }
                }
            } else if (menu.menuId + "" === menuSelect[0]) {
                openTopMenu = [menu.menuId + ""];
                return menu.children;
            }
        }
        return [];
    })();
    const UserInfo = ({visible, type, title, xform, dispatch, confirmLoading}) => {
        const formItemLayout = {
            labelCol: {
                xs: {span: 24},
                sm: {span: 6},
            },
            wrapperCol: {
                xs: {span: 24},
                sm: {span: 14},
            },
        };


        const WrappedForm = Form.create()(({form}) => {

            let treeData = xform.organization;
            if (!R.isNil(treeData)) {
                treeData = treeData.map(node => {
                    return convertOrganizations(node);
                });
            }
            let allRoles = xform.roles;
            const {getFieldDecorator, validateFields} = form;

            return (
                <Modal visible={visible} title={title} confirmLoading={confirmLoading} onCancel={
                    () => {
                        dispatch({
                            type: 'app/setEditModel',
                            payload: {
                                showStatus: false
                            }
                        });
                    }
                } onOk={
                    () => {
                        validateFields((errors, values) => {
                            if (errors) {
                                return
                            }
                            dispatch({
                                type: 'app/updateUser',
                                payload: {
                                    userId: xform.userId,
                                    username: values.username,
                                    loginId: values.loginId,
                                    mobile: values.mobile,
                                    email: values.email,
                                    orgIds: values.orgIds,
                                    roleIds: values.roleIds,
                                }
                            });
                        });
                    }
                }>
                    {(() => {
                        return (
                            <Form>
                                <FormItem
                                    {...formItemLayout}
                                    label="登录名"
                                    hasFeedback
                                >
                                    {getFieldDecorator('loginId', {
                                        rules: [{
                                            required: true, message: '请输入登录名',
                                        }],
                                        initialValue: xform.loginId
                                    })(
                                        <Input disabled={true} prefix={<Icon type="user" style={{fontSize: 13}}/>}/>
                                    )}
                                </FormItem>
                                <FormItem
                                    {...formItemLayout}
                                    label="用户名"
                                    hasFeedback
                                >
                                    {getFieldDecorator('username', {
                                        rules: [{
                                            required: true, message: '请输入用户名',
                                        }],
                                        initialValue: xform.username
                                    })(
                                        <Input/>
                                    )}
                                </FormItem>
                                <FormItem
                                    {...formItemLayout}
                                    label="手机号码"
                                    hasFeedback
                                >
                                    {getFieldDecorator('mobile', {
                                        rules: [{
                                            required: true, message: '请输入手机号码',
                                        }],
                                        initialValue: xform.mobile
                                    })(
                                        <Input/>
                                    )}
                                </FormItem>
                                <FormItem
                                    {...formItemLayout}
                                    label="邮箱"
                                    hasFeedback
                                >
                                    {getFieldDecorator('email', {
                                        rules: [{
                                            required: true, message: '请输入邮箱地址',
                                        }],
                                        initialValue: xform.email
                                    })(
                                        <Input/>
                                    )}
                                </FormItem>
                                <FormItem
                                    {...formItemLayout}
                                    label="组织机构"
                                    hasFeedback
                                >
                                    {getFieldDecorator('orgIds', {
                                        rules: [{
                                            required: true, message: '请选择组织机构',
                                        }],
                                        initialValue: xform.orgIds
                                    })(
                                        <TreeSelect
                                            disabled={true}
                                            dropdownStyle={{maxHeight: 400, overflow: 'auto'}}
                                            treeData={treeData}
                                            placeholder="请选择归属组织"
                                            allowClear
                                            multiple
                                            treeDefaultExpandAll
                                            filterTreeNode={(inputValue, treeNode) => {
                                                if (treeNode.props.title.toLowerCase().indexOf(inputValue) != -1) {
                                                    return true;
                                                }
                                                return false;
                                            }}
                                        />
                                    )}
                                </FormItem>
                                <FormItem
                                    {...formItemLayout}
                                    label="角色"
                                    hasFeedback
                                >
                                    {getFieldDecorator('roleIds', {
                                        rules: [{
                                            required: true, message: '请选择角色',
                                        }],
                                        initialValue: xform.roleIds
                                    })(
                                        <Select disabled={true} mode="tags" size={"large"} placeholder="角色可选择多个"
                                                style={{width: '100%'}} showSearch
                                                filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                        >
                                            {
                                                !R.isNil(allRoles) ? allRoles.map(item => {
                                                    return (<Select.Option value={item.roleId + ""}
                                                                           key={item.roleId + ""}>{item.desc}</Select.Option>);
                                                }) : ''
                                            }
                                        </Select>
                                    )}
                                </FormItem>
                            </Form>
                        );


                    })()}
                </Modal>
            );
        });

        return (
            <WrappedForm/>
        );
    }


    const ResetPassword = ({showResetPassword, dispatch}) => {

        const formItemLayout = {
            labelCol: {
                xs: {span: 24},
                sm: {span: 6},
            },
            wrapperCol: {
                xs: {span: 24},
                sm: {span: 14},
            },
        };


        const WrappedForm = Form.create()(({form}) => {
            const {getFieldDecorator, validateFields} = form;
            return (
                <Modal visible={showResetPassword} title={"修改密码"} onCancel={
                    () => {
                        dispatch({
                            type: 'app/setShowResetPassword',
                            payload: {
                                showResetPassword: false
                            }
                        });
                    }
                } onOk={
                    () => {
                        validateFields((errors, values) => {
                            if (errors) {
                                return
                            }
                            if (values.loginPwd != values.confirmLoginPwd) {
                                message.error("两次输入的密码不一致")
                            } else {
                                dispatch({
                                    type: 'app/modifyPassword',
                                    payload: {
                                        oldPassword: values.oldPassword,
                                        loginPwd: values.loginPwd,
                                        onSuccess: () => {
                                            dispatch({
                                                type: 'app/setShowResetPassword',
                                                payload: {
                                                    showResetPassword: false
                                                }
                                            });
                                        }
                                    }
                                });
                            }
                        });
                    }
                }>
                    <Form>
                        <FormItem
                            {...formItemLayout}
                            label="旧密码"
                            hasFeedback
                        >
                            {getFieldDecorator('oldPassword', {
                                rules: [{
                                    required: true, message: '请输入旧密码',
                                }],
                            })(
                                <Input type={'password'} prefix={<Icon type="lock" style={{fontSize: 13}}/>}/>
                            )}
                        </FormItem>
                        <FormItem
                            {...formItemLayout}
                            label="新密码"
                            hasFeedback
                        >
                            {getFieldDecorator('loginPwd', {
                                rules: [
                                    {required: true, message: '请输入新密码'},
                                    {pattern: validator.password.pattern, message: validator.password.message},
                                ],
                            })(
                                <Input type={'password'} prefix={<Icon type="lock" style={{fontSize: 13}}/>}/>
                            )}
                        </FormItem>
                        <FormItem
                            {...formItemLayout}
                            label="确认密码"
                            hasFeedback
                        >
                            {getFieldDecorator('confirmLoginPwd', {
                                rules: [
                                    {required: true, message: '请输入确认密码'},
                                    {pattern: validator.password.pattern, message: validator.password.message},
                                ],
                            })(
                                <Input type={'password'} prefix={<Icon type="lock" style={{fontSize: 13}}/>}/>
                            )}
                        </FormItem>
                    </Form>
                </Modal>
            );
        });
        return (
            <WrappedForm/>
        );
    }


    const menu = (
        <Menu>
            {/*             <Menu.Item key="0">
                <a href="http://www.alipay.com/">实名认证</a>
            </Menu.Item> */}
            <Menu.Item key="1">
                <a href="#" onClick={
                    () => {
                        dispatch({
                            type: 'app/setShowResetPassword',
                            payload: {
                                showResetPassword: true
                            }
                        });
                    }
                }>修改密码</a>
            </Menu.Item>
            <Menu.Divider/>
            <Menu.Item key="2">
                <a href="#" onClick={() => {
                    dispatch({type: 'app/queryOrganizations'});
                    dispatch({type: 'app/queryAllRoleList'});
                    dispatch({type: 'app/getUserInfo', payload: {}});
                }}>用户信息</a>
            </Menu.Item>
            <Menu.Divider/>
            <Menu.Item key="3">
                <Link to={"/logout"}>退出登录</Link>
            </Menu.Item>

        </Menu>
    );

    function itemRender(route, params, routes, paths) {
        return <span>{route.breadcrumbName}</span>;
    }

    return (
        <div>
            <Layout className="components-layout-demo-top-side-2">
                <Header style={{padding: '0 15px'}}>
                    <div style={{float: 'left', fontSize: '20px', color: '#ccc808', width: 'auto'}}>
                        <Icon type="chrome"/>
                        <span style={{marginLeft: 10}}>{ sessionStorage.lesseeNameCn}</span>
                    </div>
                    <div style={{float: 'right', color: '#ccc808'}}>
                        <Dropdown overlay={menu} trigger={['click']}>
                            <a className="ant-dropdown-link" href="#">
                                {sessionStorage.getItem("userName")} <Icon type="down"/>
                            </a>
                        </Dropdown>
                    </div>
                    {
                        (() => {
                            return (
                                <Menu
                                    theme="dark"
                                    mode="horizontal"
                                    defaultSelectedKeys={openTopMenu}
                                    style={{lineHeight: '64px'}}
                                >
                                    {
                                        menus.map((menu => {
                                            return (
                                                <Menu.Item key={menu.menuId + ""}>
                                                    <Link to={menu.url} onClick={() => {
                                                        dispatch({
                                                            type: 'app/setMenuSelect',
                                                            menuSelect: [menu.menuId + ""]
                                                        });
                                                        if (menu.children.length > 0) {
                                                            dispatch({
                                                                type: 'app/setLayoutMode',
                                                                layoutMode: 'navigate'
                                                            });
                                                        } else {
                                                            dispatch({
                                                                type: 'app/setLayoutMode',
                                                                layoutMode: 'blank'
                                                            });
                                                        }
                                                    }}>{menu.menuName}</Link>
                                                </Menu.Item>
                                            );
                                        }))
                                    }
                                </Menu>
                            );
                        })()
                    }
                </Header>
                {(() => {
                    if (sideMenus.length == 0) {
                        return (
                            <Layout>
                                {isDisplayBreadcrumb ? <Breadcrumb routes={routes} itemRender={itemRender}
                                                                   style={{margin: '12px 0'}}></Breadcrumb> : ''}
                                <Content
                                    style={{
                                        background: '#fff',
                                        padding: '20px 24px 0 24px',
                                        margin: 0,
                                        minHeight: 280
                                    }}>
                                    {children}
                                </Content>
                            </Layout>
                        );
                    } else {
                        return (
                            <Layout>
                                <style>{`
                                        .ant-layout-sider-trigger {
                                            height: 60px;
                                            line-height: 60px;
                                            background: #fff;
                                            opacity: 0;
                                `}</style>

                                <Sider
                                    collapsible
                                    breakpoint="lg"
                                    width={200}
                                    collapsedWidth={62}
                                    style={{background: '#fff', minHeight: "100vh"}}
                                >
                                    {
                                        sideMenus.length > 0 ? (() => {
                                            return (
                                                <Menu
                                                    mode="inline"
                                                    selectedKeys={selectMenus}
                                                    defaultOpenKeys={selectOpenMenu}
                                                    style={{height: '100%'}}
                                                >
                                                    {
                                                        sideMenus.map(menu => {
                                                            if (menu.children.length > 0) {
                                                                return (
                                                                    <SubMenu key={menu.menuId + ""} title={<span><i
                                                                        className={`iconfont icon-${menu.icon}`}/> {menu.menuName}</span>}>
                                                                        {
                                                                            menu.children.map(menu => {
                                                                                return (
                                                                                    <Menu.Item key={menu.menuId + ""}>
                                                                                        <Link to={menu.url}>
                                                                                            <Icon>
                                                                                                <i className={`iconfont icon-${menu.icon}`}/>
                                                                                            </Icon>
                                                                                            <span>{menu.menuName}</span>
                                                                                        </Link>
                                                                                    </Menu.Item>);
                                                                            })
                                                                        }
                                                                    </SubMenu>
                                                                );
                                                            }
                                                            return (
                                                                <Menu.Item key={menu.menuId + ""}>
                                                                    <Link to={menu.url}>
                                                                        <Icon>
                                                                            <i className={`iconfont icon-${menu.icon}`}/>
                                                                        </Icon>
                                                                        <span>{menu.menuName}</span>
                                                                    </Link>
                                                                </Menu.Item>);
                                                        })
                                                    }
                                                </Menu>
                                            );
                                        })() : ''
                                    }
                                </Sider>
                                <Layout style={{padding: '0 24px 24px'}}>
                                    {isDisplayBreadcrumb ? <Breadcrumb routes={routes} itemRender={itemRender}
                                                                       style={{margin: '12px 0'}}></Breadcrumb> : ''}

                                    <Content style={{background: '#fff', padding: 24, margin: 0, minHeight: 280}}>
                                        {children}
                                    </Content>
                                </Layout>
                            </Layout>
                        );
                    }
                })()}
            </Layout>
            <UserInfo visible={editModel.showStatus} type={editModel.type} xform={editModel.form}
                      title={editModel.title} confirmLoading={editModel.confirmLoading} dispatch={dispatch}/>
            <ResetPassword showResetPassword={showResetPassword} dispatch={dispatch}/>

        </div>
    );
}
export default connect(({app, login, organization, role}) => ({app, login, organization, role}))(App)
